package com.example.tuike.service;

import com.example.tuike.common.TokenBucketLimiter;
import com.example.tuike.entity.Contents;
import com.example.tuike.entity.Feeds;
import com.example.tuike.entity.FetchTask;
import com.example.tuike.entity.RssFetcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.PriorityBlockingQueue;

/*** @Author supersaiya
 * @Description TODO

 * @Date 2025/2/5 18:18

 * @Version 1.0*/
@Service
public class ContentFetchScheduler {
    @Autowired
    private FeedsService feedsService;
    @Autowired
    private ContentsService contentsService;
    @Autowired
    private PriorityBlockingQueue<FetchTask> taskQueue;
    @Autowired
    private TokenBucketLimiter limiter;

    // 每1分钟执行一次 定时抓取所有订阅源
    @Scheduled(fixedRate = 300000)
    public void fetchAllSources() {
        List<Feeds> sources = feedsService.getAllFeeds();
        sources.forEach(source -> {
            // 假设优先级根据某些规则设置，这里简单地设置为1
            int priority = 1;
            FetchTask task = new FetchTask(source, priority);
            taskQueue.add(task);
        });
    }

    // 定时从任务队列中取出任务并执行
    @Scheduled(fixedRate = 1000) // 每秒检查一次任务队列
    public void executeTasks() {
        while (!taskQueue.isEmpty()) {
            FetchTask task = taskQueue.poll();
            if (limiter.acquire()) {
                List<Contents> contents = RssFetcher.fetch(task.getFeed().getSourceUrl());
                for (Contents a : contents) {
                    System.out.println(a.toString());
                }
                contentsService.createContents(task.getFeed().getFeedId(), contents);
            } else {
                // 如果没有获取到令牌，将任务重新放回队列
                taskQueue.add(task);
                break; // 避免当前轮次继续处理其他任务
            }
        }
    }
}
